package com.asp.service.impl;

import com.asp.annotation.LoginCheck;
import com.asp.constant.MessageConstant;
import com.asp.context.BaseContext;
import com.asp.dto.*;
import com.asp.entity.Click;
import com.asp.entity.Topic;
import com.asp.entity.TopicDetail;
import com.asp.exception.*;
import com.asp.mapper.InteractMapper;
import com.asp.result.PageResult;
import com.asp.service.InteractService;
import com.asp.utils.AliTyUtils;
import com.asp.utils.SensitiveWordUtils;
import com.asp.vo.TopicPageQueryVO;
import com.asp.vo.TopicReplyPageQueryVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * author:          ndg
 * date:            2024/1/5
 */
@Service
@Slf4j
public class InteractServiceImpl implements InteractService {

    @Autowired
    private InteractMapper interactMapper;

    @Autowired
    private AliTyUtils aliTyUtils;

    /*用户发布主题*/
    @Override
    @LoginCheck
    @Transactional(rollbackFor = Exception.class) //无论什么 异常 都会回滚 事务控制
    public void addTopic(AddTopicDTO addTopicDTO) {
        if (SensitiveWordUtils.containsSensitiveWord(addTopicDTO.getContent()) || SensitiveWordUtils.containsSensitiveWord(addTopicDTO.getTitle())) {
            throw new SensitiveWordException(MessageConstant.SENSITIVE_WORD);
        }
        // 构造topic 对象
        Topic topic = new Topic();

        BeanUtils.copyProperties(addTopicDTO, topic);
        topic.setClick(0);
        //插入tb_topic 表
        interactMapper.insertTopic(topic);
        Integer topicId = topic.getTopicId();

        //调用ai对话 ，
        String question = topic.getTitle();
        AiAskDTO aiAskDTO = new AiAskDTO();
        aiAskDTO.setQuestion(question);

        String answer = aliTyUtils.start(aiAskDTO.getQuestion());

        // 调用发表评论
        ReplyAddDTO replyAddDTO = new ReplyAddDTO(topicId, "ai", answer);
        replyAdd(replyAddDTO);
    }

    @Override
    @LoginCheck
    public PageResult pageQuery(TopicPageQueryDTO topicPageQueryDTO) {
        PageHelper.startPage(topicPageQueryDTO.getPage(), topicPageQueryDTO.getPageSize());
        Page<TopicPageQueryVO> page = interactMapper.pageQuery(topicPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /*主题细节展示*/
    @Override
    public Topic topicDetail(Integer topicId) {
        Topic topic = interactMapper.selectByTopicId(topicId);
        return topic;
    }


    /*用户发表评论*/
    @Override
    @LoginCheck
    public void replyAdd(ReplyAddDTO replyAddDTO) {
        replyAddDTO.setContent(SensitiveWordUtils.filter(replyAddDTO.getContent()));
        //对象属性 复制  构造 topicDetail 对象
        TopicDetail topicDetail = new TopicDetail();
        BeanUtils.copyProperties(replyAddDTO, topicDetail);
        topicDetail.setClick(0);
        interactMapper.insertTopicDetail(topicDetail);
    }


    /*用户删除主题*/
    @Override
    @Transactional(rollbackFor = Exception.class) //无论什么 异常 都会回滚 事务控制
    public void topicDelete(Integer topicId) {
        //删除主题表中数据（确保 时当前登录用户删除自己发布的主题）
        String userName = BaseContext.getCurrentUserName();
        //根据topicId 查询 出对应的userName
        Topic topic = interactMapper.selectByTopicId(topicId);
        if (!userName.equals(topic.getUserName())) {
            throw new NotPermissionException(MessageConstant.NOT_PERMISSION);
        }
        interactMapper.deleteTopic(topicId);
        //删除主题细节表中的数据
        interactMapper.deleteTopicDetailByTopicId(topicId);
        //删除click 表中的数据
        interactMapper.deleteClickByTopicId(topicId);
    }

    /*用户评论分页展示*/
    @Override
    public PageResult topicReply(TopicReplyPageQueryDTO topicReplyPageQueryDTO) {
        String userName = BaseContext.getCurrentUserName();
        PageHelper.startPage(topicReplyPageQueryDTO.getPage(), topicReplyPageQueryDTO.getPageSize());
        Page<TopicReplyPageQueryVO> page = interactMapper.selectReplyByTopicId(topicReplyPageQueryDTO.getTopicId(), userName);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /*用户主题点赞*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @LoginCheck
    public void topicClick(TopicClickDTO topicClickDTO) {
        //判断该主题是否存在
        Topic topic = interactMapper.selectByTopicId(topicClickDTO.getTopicId());
        if (topic == null) {
            throw new TopicNotFoundException(MessageConstant.TOPIC_NOT_FOUND);
        }
        //判断用户 是否已经给这个主题点赞  ，如果已经点赞  抛出异常
        Click click = interactMapper.selectClickByUserNameAndTopicId(topicClickDTO);
        if (click != null) {
            throw new ClickAlreadyExistException(MessageConstant.Click_ALREADY_EXISTS);
        }
        // 没有点赞 ，插入 click表
        Click c = Click.builder()
                .userName(topicClickDTO.getUserName())
                .topicId(topicClickDTO.getTopicId())
                .build();
        interactMapper.insertClick(c);
        //插入成功后哦  修改 对应的 click数据
        interactMapper.updateTopic(topicClickDTO.getTopicId());
    }


    /*用户评论点赞*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @LoginCheck
    public void replyClick(TopicReplyClickDTO topicReplyClickDTO) {
        //判断评论是否存在
        TopicDetail topicDetail = interactMapper.selectTopicDetailByTopicDetailId(topicReplyClickDTO.getTopicDetailId());
        if (topicDetail == null) {
            throw new TopicDetailNotFoundException(MessageConstant.TOPIC_DETAIL_NOT_FOUND);
        }
        //判断用户是否已经给这个 评论点赞，如果已经点赞抛出异常
        Click click = interactMapper.selectClickByUserNameAndTopicDetailId(topicReplyClickDTO);
        //没有点赞  插入click 表
        if (click != null) {
            throw new ClickAlreadyExistException(MessageConstant.Click_ALREADY_EXISTS);
        }
        Click c = Click.builder()
                .userName(topicReplyClickDTO.getUserName())
                .topicDetailId(topicReplyClickDTO.getTopicDetailId())
                .build();

        interactMapper.insertClick(c);
        // 修改topic——detail 表中 click字段
        interactMapper.updateTpoicDetail(topicReplyClickDTO.getTopicDetailId());
    }


    /*用户删除评论*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @LoginCheck
    public void replyDelete(ReplyDeleteDTO replyDeleteDTO) {
        //判断 评论所在的主题是否是当前用户的
        Topic topic = interactMapper.selectByTopicId(replyDeleteDTO.getTopicId());
        TopicDetail topicDetail = interactMapper.selectTopicDetailByTopicDetailId(replyDeleteDTO.getTopicDetailId());
        //如果是当前用户的  ，则可以删除
        if (topic.getUserName().equals(replyDeleteDTO.getUserName()) ||
                topicDetail.getUserName().equals(replyDeleteDTO.getUserName())) {

            interactMapper.deleteTopicDetailByTopicDetailId(replyDeleteDTO.getTopicDetailId());
            //删除点赞表中相关内容
            interactMapper.deleteClickByTopicDetailId(replyDeleteDTO.getTopicDetailId());
        } else {
            throw new NotPermissionException(MessageConstant.NOT_PERMISSION);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LoginCheck
    public void topicUnClick(TopicClickDTO topicClickDTO) {
        //删除 click 表格数据
        interactMapper.deleteClickByTopicIdAndUserName(topicClickDTO);
        // 跟新 topic 表格数据
        interactMapper.updateTopic(topicClickDTO.getTopicId());
    }


    /*取消评论点赞*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @LoginCheck
    public void replyUnClick(TopicReplyClickDTO topicReplyClickDTO) {
        //删除 click 表格数据
        interactMapper.deleteClickByTopicDetailIdAndUserName(topicReplyClickDTO);
        // 跟新 topicDetail 表格数据
        interactMapper.updateTpoicDetail(topicReplyClickDTO.getTopicDetailId());
    }
}
